package com.uziot.bucket.guava.web;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @author shidt
 * @version V1.0
 * @className GuavaCacheService
 * @date 2020-11-30 23:17:46
 * @description
 */
@Slf4j
@Service
public class GuavaCacheService {

    /**
     * 创建对象缓存
     */
    LoadingCache<String, Object> objectLoadingCache =
            CacheBuilder.newBuilder()
                    // maximum 100 records can be cached
                    .maximumSize(100)
                    // cache will expire after 30 minutes of access
                    .expireAfterAccess(10, TimeUnit.SECONDS)
                    // build the cacheloader
                    .build(new CacheLoader<String, Object>() {
                        @Override
                        @SuppressWarnings("NullableProblems")
                        public Object load(String id) throws Exception {
                            log.info("正在从链接数据库查询的结果：" + id);
                            ArrayList<String> strings = new ArrayList<>();
                            strings.add("客户信息");
                            return strings;
                        }
                    });


    public Object selectById(String id) throws ExecutionException {
        System.out.println("正在根据ID查询数据：" + id);
        return objectLoadingCache.get(id);
    }


}
